package com.gupt.reggie.common;/*
@author name
@data 2023/4/19-10:34
*/

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;


@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {   //元数据处理器

    /**
     * 当insert时自动填充 employee里的实体类的公共值 ：createUser  UpdateUser等属性值
     * @param metaObject 元对象
     */

    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("自动填充公共字段【insert】");
        metaObject.setValue("createTime", LocalDateTime.now());
        metaObject.setValue("updateTime", LocalDateTime.now());
        metaObject.setValue("createUser", BaseContext.getCurrentId());//通过线程ThreadLocal动态获取当前用户id
        metaObject.setValue("updateUser", BaseContext.getCurrentId());
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("自动填充公共字段【update】");

        long id = Thread.currentThread().getId();   //验证controller filter ObjectHandler 为同一个线程
        log.info("当前线程id为：{}",id);

        metaObject.setValue("updateTime", LocalDateTime.now());
        metaObject.setValue("updateUser", BaseContext.getCurrentId());
    }
}
